package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/registerFindServlet")
public class RegisterFindServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取id
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        /*
         *
         * */
        //获取参数集合
        Map<String, String[]> map = request.getParameterMap();
        /*封装User对象
        * */
        User registerUser=new User();
        try {
            BeanUtils.populate(registerUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        /*
        * 2调用service查询*/
        UserService service=new UserServiceImpl();
        User user =service.findUserById(id);
        /*3将user存入request
         *
         * */
        if (user!=null){

        request.setAttribute("user",user);
        request.setAttribute("exist","账号已经存在");
        request.getRequestDispatcher("/register.jsp").forward(request,response);
        }else{
            request.setAttribute("id",registerUser.getId());
            request.setAttribute("username",registerUser.getUsername());
            request.setAttribute("password",registerUser.getPassword());
            request.setAttribute("remark",registerUser.getRemark());
            request.setAttribute("position",registerUser.getPosition());
            request.getRequestDispatcher("/registerServlet").forward(request,response);
//            response.sendRedirect(request.getContextPath()+"/registerServlet");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
